<script lang="ts" setup>
import { ref, computed, onMounted, watch, provide } from 'vue';
import NavigationSidebar from '@/components/NavigationSidebar.vue';
import ContentArea from '@/components/ContentArea.vue';
import defaultNavigationData from '@/data/navigation.json';

// 定义导航数据结构
interface NavItem {
  id: string;
  name: string;
  icon?: string;
}

interface Website {
  id: string;
  title: string;
  url: string;
  icon: string;
  description?: string;
}

interface Category {
  id: string;
  name: string;
  websites: Website[];
}

// 导航菜单数据
const navItems = ref<NavItem[]>([]);

// 内容数据
const categories = ref<Category[]>([]);

// 加载状态
const loading = ref<boolean>(true);

// 当前选中的导航项
const activeNav = ref<string>('recommend');

// 设置弹窗相关状态
const showSettingsModal = ref<boolean>(false);
const activeSettingsTab = ref<string>('data');


const emit = defineEmits<{
  (e: 'import-data'): void;
  (e: 'export-data'): void;
  (e: 'update-website', website: Website, categoryId: string, subCategoryName?: string): void;
  (e: 'delete-website', websiteId: string): void;
  (e: 'add-website', website: Website, categoryId: string, subCategoryName?: string): void;
}>();

// 处理更新网站
const handleUpdateWebsite = async (website: Website, categoryId: string, subCategoryName?: string) => {
  console.log('更新网站:', website, categoryId, subCategoryName);
  
  try {
    // 查找目标分类
    const categoryIndex = categories.value.findIndex(c => c.id === categoryId);
    if (categoryIndex === -1) {
      console.error('未找到指定分类');
      return;
    }
    
    // 创建新分类数组（避免直接修改响应式数据）
    const updatedCategories = [...categories.value];
    const updatedCategory = { ...updatedCategories[categoryIndex] };
    
    // 先从所有分类和子分类中移除该网站
    for (let i = 0; i < updatedCategories.length; i++) {
      // 从主分类中移除
      updatedCategories[i].websites = updatedCategories[i].websites.filter(w => w.id !== website.id);
      
      // 从子分类中移除
      if (updatedCategories[i].subCategories) {
        for (let j = 0; j < updatedCategories[i].subCategories.length; j++) {
          updatedCategories[i].subCategories[j].websites = 
            updatedCategories[i].subCategories[j].websites.filter(w => w.id !== website.id);
        }
      }
    }
    
    // 然后添加到指定分类
    if (subCategoryName) {
      // 查找或创建子分类
      let subCategoryIndex = -1;
      if (updatedCategory.subCategories) {
        subCategoryIndex = updatedCategory.subCategories.findIndex(sc => sc.name === subCategoryName);
      } else {
        updatedCategory.subCategories = [];
      }
      
      if (subCategoryIndex === -1) {
        // 创建新的子分类
        const newSubCategory: SubCategory = {
          id: `${categoryId}-${Date.now()}`,
          name: subCategoryName,
          websites: [website]
        };
        updatedCategory.subCategories.push(newSubCategory);
      } else {
        // 添加到现有子分类
        updatedCategory.subCategories[subCategoryIndex] = {
          ...updatedCategory.subCategories[subCategoryIndex],
          websites: [...updatedCategory.subCategories[subCategoryIndex].websites, website]
        };
      }
    } else {
      // 添加到主分类
      updatedCategory.websites = [...updatedCategory.websites, website];
    }
    
    // 更新分类
    updatedCategories[categoryIndex] = updatedCategory;
    categories.value = updatedCategories;
    
    // 保存到 Chrome 存储
    const dataToSave = {
      navItems: navItems.value,
      categories: categories.value
    };
    
    if (typeof chrome !== 'undefined' && chrome.storage) {
      await chrome.storage.local.set({ navigationData: dataToSave });
    }
    
    // 自动同步到Git
    if (gitConfig.value.isConfigured) {
      await uploadToGit();
    }
    
    console.log('网站更新成功');
  } catch (error) {
    console.error('更新网站失败:', error);
    alert('更新网站失败: ' + (error as Error).message);
  }
};

// Git同步配置
const gitConfig = ref({
  provider: 'gitee', // 'gitee' 或 'github'
  token: '2de0cf5c3632b0823f7f05251d5011bf',
  owner: 'ifeiyang',
  repo: 'my-favorite',
  filePath: 'navigation-data.json',
  isConfigured: false
});

// 设置弹窗中的标签页
const settingsTabs = ref([
  { id: 'data', name: '数据管理' },
  { id: 'git-sync', name: 'Git同步' },
  { id: 'appearance', name: '外观设置' },
  { id: 'advanced', name: '高级设置' }
]);

// 处理导航切换
const handleNavChange = (navId: string) => {
  console.log('导航切换到:', navId);
  activeNav.value = navId;
  console.log('当前activeNav值:', activeNav.value);
};

// 获取当前选中分类的数据
const currentCategory = computed(() => {
  console.log('计算currentCategory, 当前activeNav:', activeNav.value);
  console.log('所有分类:', categories.value);
  const category = categories.value.find(category => category.id === activeNav.value);
  console.log('找到的分类:', category);
  return category;
});

// 监听activeNav变化
watch(activeNav, (newVal, oldVal) => {
  console.log('activeNav changed from', oldVal, 'to', newVal);
  console.log('当前currentCategory:', currentCategory.value);
});

// 从 Chrome 存储加载用户自定义数据，如果没有则使用默认数据
const loadNavigationData = async () => {
  try {
    let navigationData;
    
    // 尝试从 Chrome 存储获取用户自定义数据
    if (typeof chrome !== 'undefined' && chrome.storage) {
      const result = await chrome.storage.local.get(['navigationData', 'gitConfig']);
      navigationData = result.navigationData;
      if (result.gitConfig) {
        gitConfig.value = { ...gitConfig.value, ...result.gitConfig };
      }
    }
    
    // 如果没有用户自定义数据，则使用默认数据
    if (!navigationData) {
      navigationData = defaultNavigationData;
    }
    
    // 设置导航数据
    navItems.value = navigationData.navItems;
    categories.value = navigationData.categories;
    
    console.log('加载的导航项:', navItems.value);
    console.log('加载的分类:', categories.value);
    
    // 设置默认选中项
    if (navigationData.navItems.length > 0) {
      activeNav.value = navigationData.navItems[0].id;
      console.log('设置默认选中项:', activeNav.value);
    }
    
    // 提供全局导航数据
    provide('navigationData', navigationData);
  } catch (error) {
    console.error('Failed to load navigation data:', error);
  } finally {
    loading.value = false;
  }
};

// 导入本地 JSON 文件的功能
const importNavigationData = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.json';
  
  input.onchange = async (event) => {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (!file) return;
    
    try {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const data = JSON.parse(e.target?.result as string);
          
          // 验证数据结构
          if (!data.navItems || !data.categories) {
            throw new Error('Invalid navigation data structure');
          }
          
          // 保存到 Chrome 存储
          if (typeof chrome !== 'undefined' && chrome.storage) {
            await chrome.storage.local.set({ navigationData: data });
          }
          
          // 更新当前数据
          navItems.value = data.navItems;
          categories.value = data.categories;
          
          // 重置选中项
          if (data.navItems.length > 0) {
            activeNav.value = data.navItems[0].id;
          }
          
          // 更新提供的数据
          provide('navigationData', data);
          
          console.log('成功导入导航数据');
        } catch (error) {
          console.error('导入数据失败:', error);
          alert('导入失败：文件格式不正确');
        }
      };
      reader.readAsText(file);
    } catch (error) {
      console.error('读取文件失败:', error);
    }
  };
  
  input.click();
};

// 导出当前数据为 JSON 文件
const exportNavigationData = () => {
  const data = {
    navItems: navItems.value,
    categories: categories.value
  };
  
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = 'navigation-data.json';
  document.body.appendChild(a);
  a.click();
  
  // 清理
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 100);
};

// 保存Git配置
const saveGitConfig = async () => {
  // 更新配置状态
  const isConfigured = !!(gitConfig.value.token && gitConfig.value.owner && gitConfig.value.repo);
  const configToSave = { 
    ...gitConfig.value, 
    isConfigured 
  };
  
  if (typeof chrome !== 'undefined' && chrome.storage) {
    await chrome.storage.local.set({ gitConfig: configToSave });
  }
  
  // 更新本地状态
  gitConfig.value.isConfigured = isConfigured;
  
  alert('Git配置已保存');
};

// 处理添加网站
const handleAddWebsite = async (website: Website, categoryId: string, subCategoryName?: string) => {
  console.log('添加网站:', website, categoryId, subCategoryName);
  
  try {
    // 查找目标分类
    const categoryIndex = categories.value.findIndex(c => c.id === categoryId);
    if (categoryIndex === -1) {
      console.error('未找到指定分类');
      return;
    }
    
    // 创建新分类数组（避免直接修改响应式数据）
    const updatedCategories = [...categories.value];
    const updatedCategory = { ...updatedCategories[categoryIndex] };
    
    if (subCategoryName) {
      // 查找或创建子分类
      let subCategoryIndex = -1;
      if (updatedCategory.subCategories) {
        subCategoryIndex = updatedCategory.subCategories.findIndex(sc => sc.name === subCategoryName);
      } else {
        updatedCategory.subCategories = [];
      }
      
      if (subCategoryIndex === -1) {
        // 创建新的子分类
        const newSubCategory: SubCategory = {
          id: `${categoryId}-${Date.now()}`,
          name: subCategoryName,
          websites: [website]
        };
        updatedCategory.subCategories.push(newSubCategory);
      } else {
        // 添加到现有子分类
        updatedCategory.subCategories[subCategoryIndex] = {
          ...updatedCategory.subCategories[subCategoryIndex],
          websites: [...updatedCategory.subCategories[subCategoryIndex].websites, website]
        };
      }
    } else {
      // 添加到主分类
      updatedCategory.websites = [...updatedCategory.websites, website];
    }
    
    // 更新分类
    updatedCategories[categoryIndex] = updatedCategory;
    categories.value = updatedCategories;
    
    // 保存到 Chrome 存储
    const dataToSave = {
      navItems: navItems.value,
      categories: categories.value
    };
    
    if (typeof chrome !== 'undefined' && chrome.storage) {
      await chrome.storage.local.set({ navigationData: dataToSave });
    }
    
    // 自动同步到Git
    if (gitConfig.value.isConfigured) {
      await uploadToGit();
    }
    
    console.log('网站添加成功');
  } catch (error) {
    console.error('添加网站失败:', error);
    alert('添加网站失败: ' + (error as Error).message);
  }
};

// 上传数据到Git仓库
const uploadToGit = async () => {
  if (!gitConfig.value.isConfigured) {
    console.log('Git未配置，跳过同步');
    return;
  }

  try {
    const data = {
      navItems: navItems.value,
      categories: categories.value
    };

    const jsonData = JSON.stringify(data, null, 2);
    
    // 构建API URL
    let apiUrl = '';
    if (gitConfig.value.provider === 'gitee') {
      apiUrl = `https://gitee.com/api/v5/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
    } else {
      apiUrl = `https://api.github.com/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
    }

    // 首先获取文件信息（需要sha用于更新）
    let sha = '';
    try {
      const response = await fetch(apiUrl, {
        headers: {
          'Authorization': `token ${gitConfig.value.token}`,
          'Accept': 'application/json'
        }
      });
      
      if (response.ok) {
        const fileInfo = await response.json();
        sha = fileInfo.sha;
      }
    } catch (e) {
      console.log('文件不存在，将创建新文件');
    }

    // 上传文件
    const uploadData = {
      access_token: gitConfig.value.token,
      message: 'Update navigation data',
      content: btoa(unescape(encodeURIComponent(jsonData))), // base64编码
      branch: 'master' // 指定分支
    };

    // 如果是更新文件，需要提供sha
    let method = 'POST';
    if (sha) {
      (uploadData as any).sha = sha;
      method = 'PUT';
    }

    const response = await fetch(apiUrl, {
      method: method,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(uploadData)
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Git API Error Response:', errorText);
      throw new Error(`同步失败: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    console.log('同步成功:', result);
  } catch (error) {
    console.error('同步到Git失败:', error);
    throw new Error(`同步到Git失败: ${(error as Error).message}`);
  }
};


// 从Git仓库下载数据
const downloadFromGit = async () => {
  if (!gitConfig.value.isConfigured) {
    alert('请先配置Git同步参数');
    return;
  }

  // 添加确认对话框
  const confirmed = confirm('是否覆盖本地数据？\n此操作将用Git上的数据替换您当前的本地数据。');
  if (!confirmed) {
    return; // 用户取消操作
  }

  try {
    // 构建API URL
    let apiUrl = '';
    if (gitConfig.value.provider === 'gitee') {
      apiUrl = `https://gitee.com/api/v5/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
    } else {
      apiUrl = `https://api.github.com/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
    }

    const response = await fetch(apiUrl, {
      headers: {
        'Authorization': `token ${gitConfig.value.token}`,
        'Accept': 'application/json'
      }
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Gitee API Error Response:', errorText);
      throw new Error(`无法获取文件: ${response.status} ${response.statusText}`);
    }

    const fileInfo = await response.json();
    const content = decodeURIComponent(escape(atob(fileInfo.content)));
    const data = JSON.parse(content);

    // 验证数据结构
    if (!data.navItems || !data.categories) {
      throw new Error('无效的数据结构');
    }

    // 保存到 Chrome 存储
    if (typeof chrome !== 'undefined' && chrome.storage) {
      await chrome.storage.local.set({ navigationData: data });
    }

    // 更新当前数据
    navItems.value = data.navItems;
    categories.value = data.categories;

    // 重置选中项
    if (data.navItems.length > 0) {
      activeNav.value = data.navItems[0].id;
    }

    // 更新提供的数据
    provide('navigationData', data);

    alert('数据已成功从Git仓库下载');
  } catch (error) {
    console.error('下载失败:', error);
    alert('下载失败: ' + (error as Error).message);
  }
};

// 切换设置弹窗标签页
const switchSettingsTab = (tabId: string) => {
  activeSettingsTab.value = tabId;
};

// 显示设置弹窗
const openSettings = () => {
  showSettingsModal.value = true;
};

// 隐藏设置弹窗
const closeSettings = () => {
  showSettingsModal.value = false;
};


// Git同步增强配置
const gitSyncEnhanced = ref({
  autoSync: false,
  syncInterval: 15, // 分钟
  lastSync: null as Date | null,
  conflictResolution: 'newer' as 'newer' | 'local' | 'remote' | 'manual'
});


// 增强的Git同步功能
const enhancedGitSync = {
  // 获取远程数据
  async fetchRemoteData() {
    if (!gitConfig.value.isConfigured) {
      throw new Error('Git未配置');
    }

    try {
      // 构建API URL
      let apiUrl = '';
      if (gitConfig.value.provider === 'gitee') {
        apiUrl = `https://gitee.com/api/v5/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
      } else {
        apiUrl = `https://api.github.com/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
      }

      const response = await fetch(apiUrl, {
        headers: {
          'Authorization': `token ${gitConfig.value.token}`,
          'Accept': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`无法获取文件: ${response.status} ${response.statusText}`);
      }

      const fileInfo = await response.json();
      const content = decodeURIComponent(escape(atob(fileInfo.content)));
      const data = JSON.parse(content);
      
      // 添加时间戳信息
      return {
        data,
        timestamp: new Date(fileInfo.updated_at || fileInfo.commit?.committer?.date || new Date()),
        sha: fileInfo.sha
      };
    } catch (error) {
      console.error('获取远程数据失败:', error);
      throw error;
    }
  },

  // 上传数据到Git仓库（带时间戳）
  async uploadToGitWithTimestamp(data: any) {
    if (!gitConfig.value.isConfigured) {
      alert('请先配置Git同步参数');
      return;
    }

    try {
      // 添加时间戳
      const dataWithTimestamp = {
        ...data,
        lastModified: new Date().toISOString()
      };

      const jsonData = JSON.stringify(dataWithTimestamp, null, 2);
      
      // 构建API URL
      let apiUrl = '';
      if (gitConfig.value.provider === 'gitee') {
        apiUrl = `https://gitee.com/api/v5/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
      } else {
        apiUrl = `https://api.github.com/repos/${gitConfig.value.owner}/${gitConfig.value.repo}/contents/${gitConfig.value.filePath}`;
      }

      // 首先获取文件信息（需要sha用于更新）
      let sha = '';
      try {
        const response = await fetch(apiUrl, {
          headers: {
            'Authorization': `token ${gitConfig.value.token}`,
            'Accept': 'application/json'
          }
        });
        
        if (response.ok) {
          const fileInfo = await response.json();
          sha = fileInfo.sha;
        }
      } catch (e) {
        console.log('文件不存在，将创建新文件');
      }

      // 上传文件
      const uploadData = {
        access_token: gitConfig.value.token,
        message: `Update navigation data at ${new Date().toLocaleString()}`,
        content: btoa(unescape(encodeURIComponent(jsonData))), // base64编码
        branch: 'master' // 指定分支
      };

      // 如果是更新文件，需要提供sha
      let method = 'POST';
      if (sha) {
        (uploadData as any).sha = sha;
        method = 'PUT';
      }

      const response = await fetch(apiUrl, {
        method: method,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(uploadData)
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('Git API Error Response:', errorText);
        throw new Error(`上传失败: ${response.status} ${response.statusText}`);
      }

      const result = await response.json();
      console.log('上传成功:', result);
      
      // 更新最后同步时间
      gitSyncEnhanced.value.lastSync = new Date();
      await chrome.storage.local.set({ gitSyncEnhanced: gitSyncEnhanced.value });
      
      return result;
    } catch (error) {
      console.error('上传失败:', error);
      throw error;
    }
  },

  // 解决冲突
  resolveConflicts(localData: any, remoteData: any, strategy: 'newer' | 'local' | 'remote' | 'manual') {
    switch (strategy) {
      case 'newer':
        // 比较时间戳，选择更新的数据
        const localTime = localData.lastModified ? new Date(localData.lastModified) : new Date(0);
        const remoteTime = remoteData.timestamp ? new Date(remoteData.timestamp) : new Date(0);
        
        if (localTime > remoteTime) {
          console.log('本地数据更新，使用本地数据');
          return localData;
        } else {
          console.log('远程数据更新，使用远程数据');
          return remoteData.data;
        }
        
      case 'local':
        console.log('冲突解决策略: 使用本地数据');
        return localData;
        
      case 'remote':
        console.log('冲突解决策略: 使用远程数据');
        return remoteData.data;
        
      case 'manual':
        // 手动解决冲突（简化版，实际应用中可以提供更复杂的UI）
        const useRemote = confirm(
          '检测到数据冲突:\n' +
          `- 本地最后修改: ${localData.lastModified ? new Date(localData.lastModified).toLocaleString() : '未知'}\n` +
          `- 远程最后修改: ${remoteData.timestamp ? remoteData.timestamp.toLocaleString() : '未知'}\n\n` +
          '是否使用远程数据覆盖本地数据？\n点击"确定"使用远程数据，点击"取消"保留本地数据。'
        );
        
        return useRemote ? remoteData.data : localData;
        
      default:
        return localData;
    }
  },

  // 同步数据
  async sync() {
    try {
      // 获取本地数据
      const localData = {
        navItems: navItems.value,
        categories: categories.value,
        lastModified: new Date().toISOString()
      };

      // 获取远程数据
      const remoteData = await this.fetchRemoteData();

      // 检查是否有冲突
      const hasConflict = this.checkConflict(localData, remoteData);
      
      if (hasConflict) {
        console.log('检测到数据冲突，正在解决...');
        const resolvedData = this.resolveConflicts(
          localData, 
          remoteData, 
          gitSyncEnhanced.value.conflictResolution
        );
        
        // 上传解决后的数据
        await this.uploadToGitWithTimestamp(resolvedData);
        
        // 更新本地数据
        if (resolvedData !== localData) {
          navItems.value = resolvedData.navItems;
          categories.value = resolvedData.categories;
          
          // 保存到本地存储
          await saveNavigationData();
        }
        
        return { success: true, action: 'conflict_resolved' };
      } else {
        // 检查哪边数据更新
        const localTime = localData.lastModified ? new Date(localData.lastModified) : new Date(0);
        const remoteTime = remoteData.timestamp ? new Date(remoteData.timestamp) : new Date(0);
        
        if (localTime > remoteTime) {
          // 本地数据更新，上传到远程
          console.log('本地数据更新，正在上传到远程...');
          await this.uploadToGitWithTimestamp(localData);
          return { success: true, action: 'uploaded' };
        } else if (remoteTime > localTime) {
          // 远程数据更新，下载到本地
          console.log('远程数据更新，正在下载到本地...');
          navItems.value = remoteData.data.navItems;
          categories.value = remoteData.data.categories;
          
          // 保存到本地存储
          await saveNavigationData();
          return { success: true, action: 'downloaded' };
        } else {
          // 数据一致，无需操作
          console.log('数据已同步，无需操作');
          return { success: true, action: 'no_change' };
        }
      }
    } catch (error) {
      console.error('同步失败:', error);
      throw error;
    }
  },

  // 检查是否有冲突
  checkConflict(localData: any, remoteData: any) {
    // 简单的冲突检测：检查两边数据都有更新
    const localTime = localData.lastModified ? new Date(localData.lastModified) : new Date(0);
    const remoteTime = remoteData.timestamp ? new Date(remoteData.timestamp) : new Date(0);
    
    // 如果两边都在同一时间后有修改，则可能存在冲突
    // 这里简化处理，实际应用中可以做更详细的比较
    const timeDiff = Math.abs(localTime.getTime() - remoteTime.getTime());
    return timeDiff > 1000; // 如果时间差超过1秒，认为可能存在冲突
  }
};

// 自动同步功能
let syncIntervalId: number | null = null;

const startAutoSync = () => {
  if (syncIntervalId) {
    clearInterval(syncIntervalId);
  }
  
  if (gitSyncEnhanced.value.autoSync && gitConfig.value.isConfigured) {
    syncIntervalId = window.setInterval(async () => {
      try {
        await enhancedGitSync.sync();
        console.log('自动同步完成');
      } catch (error) {
        console.error('自动同步失败:', error);
      }
    }, gitSyncEnhanced.value.syncInterval * 60 * 1000);
  }
};

// 保存增强的Git同步配置
const saveGitSyncEnhancedConfig = async () => {
  await chrome.storage.local.set({ gitSyncEnhanced: gitSyncEnhanced.value });
  startAutoSync();
};

// 一键同步
const oneClickSync = async () => {
  if (!gitConfig.value.isConfigured) {
    alert('请先配置Git同步参数');
    return;
  }

  try {
    const result = await enhancedGitSync.sync();
    
    switch (result.action) {
      case 'conflict_resolved':
        alert('同步完成，检测到并解决了数据冲突');
        break;
      case 'uploaded':
        alert('同步完成，本地数据已上传到Git仓库');
        break;
      case 'downloaded':
        alert('同步完成，远程数据已下载到本地');
        break;
      case 'no_change':
        alert('数据已同步，无需操作');
        break;
    }
  } catch (error) {
    console.error('同步失败:', error);
    alert('同步失败: ' + (error as Error).message);
  }
};

// 组件挂载时加载增强配置
onMounted(async () => {
  console.log('组件挂载');
  // 加载增强的Git同步配置
  const result = await chrome.storage.local.get(['gitSyncEnhanced']);
  if (result.gitSyncEnhanced) {
    gitSyncEnhanced.value = { ...gitSyncEnhanced.value, ...result.gitSyncEnhanced };
  }
  
  loadNavigationData();
  startAutoSync();
});

// 组件卸载时清理定时器
window.addEventListener('beforeunload', () => {
  if (syncIntervalId) {
    clearInterval(syncIntervalId);
  }
});



// 组件挂载时加载数据
onMounted(() => {
  console.log('组件挂载');
  loadNavigationData();
});

const updateWebsite = (updatedWebsite: Website) => {
  // 查找并更新网站数据
  const categoriesCopy = [...categories.value];
  
  for (const category of categoriesCopy) {
    // 检查主分类中的网站
    const websiteIndex = category.websites.findIndex(w => w.id === updatedWebsite.id);
    if (websiteIndex !== -1) {
      category.websites[websiteIndex] = updatedWebsite;
      break;
    }
    
    // 检查子分类中的网站
    if (category.subCategories) {
      for (const subCategory of category.subCategories) {
        const subWebsiteIndex = subCategory.websites.findIndex(w => w.id === updatedWebsite.id);
        if (subWebsiteIndex !== -1) {
          subCategory.websites[subWebsiteIndex] = updatedWebsite;
          break;
        }
      }
    }
  }
  
  categories.value = categoriesCopy;
  
  // 保存到 Chrome 存储
  saveNavigationData();
};

const deleteWebsite = (websiteId: string) => {
  // 查找并删除网站数据
  const categoriesCopy = [...categories.value];
  
  for (const category of categoriesCopy) {
    // 检查主分类中的网站
    const websiteIndex = category.websites.findIndex(w => w.id === websiteId);
    if (websiteIndex !== -1) {
      category.websites.splice(websiteIndex, 1);
      break;
    }
    
    // 检查子分类中的网站
    if (category.subCategories) {
      for (const subCategory of category.subCategories) {
        const subWebsiteIndex = subCategory.websites.findIndex(w => w.id === websiteId);
        if (subWebsiteIndex !== -1) {
          subCategory.websites.splice(subWebsiteIndex, 1);
          break;
        }
      }
    }
  }
  
  categories.value = categoriesCopy;
  
  // 保存到 Chrome 存储
  saveNavigationData();
};


const addWebsite = (newWebsite: Website) => {
  // 将新网站添加到当前分类中
  const categoriesCopy = [...categories.value];
  const currentCategory = categoriesCopy.find(cat => cat.id === activeNav.value);
  
  if (currentCategory) {
    // 添加到主分类的网站列表中
    currentCategory.websites.push(newWebsite);
    categories.value = categoriesCopy;
    
    // 保存到 Chrome 存储
    saveNavigationData();
  }
};


// 保存导航数据到 Chrome 存储
const saveNavigationData = async () => {
  try {
    const data = {
      navItems: navItems.value,
      categories: categories.value
    };
    
    if (typeof chrome !== 'undefined' && chrome.storage) {
      await chrome.storage.local.set({ navigationData: data });
    }
    
    // 更新提供的数据
    provide('navigationData', data);
  } catch (error) {
    console.error('保存导航数据失败:', error);
  }
};
</script>

<template>
  <div class="navigation-container">
    <div v-if="loading" class="loading">
      加载中...
    </div>
    <template v-else>
      <NavigationSidebar 
        :nav-items="navItems" 
        :active-nav="activeNav" 
        @nav-change="handleNavChange"
        @open-settings="openSettings"
      />
      <!-- 只有当currentCategory存在时才显示内容区域 -->
      <!-- <ContentArea 
        v-if="currentCategory" 
        :category="currentCategory" 
        @import-data="importNavigationData"
        @export-data="exportNavigationData"
      /> -->

      <ContentArea v-if="currentCategory" 
        :category="currentCategory" 
        @import-data="importNavigationData"
        @export-data="exportNavigationData"
        @update-website="updateWebsite"
        @delete-website="deleteWebsite"
         @add-website="handleAddWebsite"
      />
    </template>
  </div>

  <!-- 设置弹窗 -->
  <div v-if="showSettingsModal" class="settings-modal" @click="closeSettings">
    <div class="settings-content" @click.stop>
      <div class="settings-header">
        <h2>设置</h2>
        <button class="close-btn" @click="closeSettings">×</button>
      </div>
      
      <div class="settings-tabs">
        <button
          v-for="tab in settingsTabs"
          :key="tab.id"
          class="tab-button"
          :class="{ active: activeSettingsTab === tab.id }"
          @click="switchSettingsTab(tab.id)"
        >
          {{ tab.name }}
        </button>
      </div>
      
      <div class="settings-body">
        <!-- 数据管理标签页 -->
        <div v-if="activeSettingsTab === 'data'" class="tab-content">
          <div class="setting-item">
            <h3>本地数据管理</h3>
            <div class="setting-actions">
              <button class="action-button" @click="importNavigationData">导入数据</button>
              <button class="action-button" @click="exportNavigationData">导出数据</button>
            </div>
          </div>
        </div>
        
        <!-- Git同步标签页 -->
        <div v-if="activeSettingsTab === 'git-sync'" class="tab-content">
          <div class="setting-item">
            <h3>Git同步配置</h3>
            <div class="form-group">
              <label>平台选择:</label>
              <select v-model="gitConfig.provider" class="form-control">
                <option value="gitee">Gitee</option>
                <option value="github">GitHub</option>
              </select>
            </div>
            
            <div class="form-group">
              <label>访问令牌 (Token):</label>
              <input 
                v-model="gitConfig.token" 
                type="password" 
                class="form-control" 
                placeholder="请输入访问令牌"
              />
              <p class="help-text">请在Gitee/GitHub上生成个人访问令牌</p>
            </div>
            
            <div class="form-group">
              <label>仓库所有者 (Owner):</label>
              <input 
                v-model="gitConfig.owner" 
                type="text" 
                class="form-control" 
                placeholder="例如: your-username"
              />
            </div>
            
            <div class="form-group">
              <label>仓库名称 (Repo):</label>
              <input 
                v-model="gitConfig.repo" 
                type="text" 
                class="form-control" 
                placeholder="例如: my-navigation-data"
              />
            </div>
            
            <div class="form-group">
              <label>文件路径 (File Path):</label>
              <input 
                v-model="gitConfig.filePath" 
                type="text" 
                class="form-control" 
                placeholder="例如: navigation-data.json"
              />
            </div>
            
            <div class="setting-actions">
              <button class="action-button" @click="saveGitConfig">保存配置</button>
            </div>
            
            <!-- 增强的Git同步选项 -->
            <div v-if="gitConfig.isConfigured" class="enhanced-git-options">
              <h4>增强同步选项</h4>
              
              <div class="form-group">
                <label>
                  <input 
                    type="checkbox" 
                    v-model="gitSyncEnhanced.autoSync"
                    @change="saveGitSyncEnhancedConfig"
                  /> 启用自动同步
                </label>
              </div>
              
              <div class="form-group" v-if="gitSyncEnhanced.autoSync">
                <label>同步间隔 (分钟):</label>
                <input 
                  v-model.number="gitSyncEnhanced.syncInterval" 
                  type="number" 
                  min="1"
                  max="1440"
                  class="form-control"
                  @change="saveGitSyncEnhancedConfig"
                />
              </div>
              
              <div class="form-group">
                <label>冲突解决策略:</label>
                <select 
                  v-model="gitSyncEnhanced.conflictResolution" 
                  class="form-control"
                  @change="saveGitSyncEnhancedConfig"
                >
                  <option value="newer">使用更新的数据</option>
                  <option value="local">始终使用本地数据</option>
                  <option value="remote">始终使用远程数据</option>
                  <option value="manual">手动选择</option>
                </select>
              </div>
              
              <div class="setting-actions">
                <button class="action-button" @click="oneClickSync">一键同步</button>
              </div>
              
              <div v-if="gitSyncEnhanced.lastSync" class="help-text">
                上次同步时间: {{ gitSyncEnhanced.lastSync.toLocaleString() }}
              </div>
            </div>
            
            <div class="setting-actions">
              <button 
                class="action-button" 
                @click="uploadToGit" 
                :disabled="!gitConfig.isConfigured"
              >
                上传到Git
              </button>
              <button 
                class="action-button" 
                @click="downloadFromGit" 
                :disabled="!gitConfig.isConfigured"
              >
                从Git下载
              </button>
            </div>
            
            <div class="help-text">
              <p>使用说明:</p>
              <ol>
                <li>在Gitee/GitHub上创建一个私有仓库用于存储数据</li>
                <li>生成个人访问令牌并填入上面的Token字段</li>
                <li>填写仓库信息并保存配置</li>
                <li>使用上传/下载功能进行数据同步</li>
              </ol>
            </div>
          </div>
        </div>
        
        <!-- 外观设置标签页 -->
        <div v-if="activeSettingsTab === 'appearance'" class="tab-content">
          <div class="setting-item">
            <h3>外观设置</h3>
            <p>此功能尚未实现</p>
          </div>
        </div>
        
        <!-- 高级设置标签页 -->
        <div v-if="activeSettingsTab === 'advanced'" class="tab-content">
          <div class="setting-item">
            <h3>高级设置</h3>
            <p>此功能尚未实现</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.navigation-container {
  display: flex;
  min-height: 100vh;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
}

/* 设置弹窗样式 */
.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.settings-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 80%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.settings-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.close-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

.settings-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

.tab-button {
  padding: 12px 20px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
}

.tab-button:hover {
  background-color: #f5f5f5;
}

.tab-button.active {
  color: #3498db;
  border-bottom-color: #3498db;
}

.settings-body {
  flex: 1;
  overflow-y: auto;
}

.tab-content {
  padding: 20px;
}

.setting-item {
  margin-bottom: 20px;
}

.setting-item h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.setting-actions {
  display: flex;
  gap: 10px;
  margin: 15px 0;
  flex-wrap: wrap;
}

.action-button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.action-button:hover {
  background-color: #2980b9;
}

.action-button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.help-text {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 5px;
}

.help-text ol {
  padding-left: 20px;
  margin: 10px 0;
}

@media (max-width: 768px) {
  .navigation-container {
    flex-direction: column;
  }
  
  .settings-content {
    width: 95%;
  }
  
  .setting-actions {
    flex-direction: column;
  }
}

.enhanced-git-options {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.enhanced-git-options h4 {
  margin-top: 0;
  margin-bottom: 15px;
  font-weight: 600;
}
</style>
